from flask_login import UserMixin # type: ignore
from datetime import datetime, timedelta
import secrets  # 用于生成token
from api import db

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    phone = db.Column(db.String(11), unique=True, nullable=False, comment='手机号')
    password = db.Column(db.String(128), nullable=False, comment='密码')
    name = db.Column(db.String(50), nullable=False, comment='用户名')
    gender = db.Column(db.Integer, default=0, comment='性别：0-未知，1-男，2-女')
    openid = db.Column(db.String(32), unique=True, nullable=True, comment='微信openid')
    description = db.Column(db.String(500), nullable=True, comment='个人简介')
    avatar = db.Column(db.String(255), nullable=True, comment='头像URL')
    token = db.Column(db.String(100), unique=True, nullable=True, comment='登录token')
    token_expired = db.Column(db.DateTime, nullable=True, comment='token过期时间')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    def generate_token(self, expires_in=7*24*60*60):
        """生成新的token"""
        self.token = secrets.token_urlsafe(32)
        self.token_expired = datetime.utcnow() + timedelta(seconds=expires_in)
        return self.token

    def check_token(self):
        """检查token是否有效"""
        if not self.token or not self.token_expired:
            return False
        return datetime.utcnow() <= self.token_expired

    def to_dict(self):
        return {
            'id': self.id,
            'phone': self.phone,
            'name': self.name,
            'gender': self.gender,
            'description': self.description,
            'avatar': self.avatar,
            'openid': self.openid,
            'token': self.token,
            'create_time': int(datetime.timestamp(self.create_time)) if self.create_time else None,
            'update_time': int(datetime.timestamp(self.update_time)) if self.update_time else None
        }

class VerificationCode(db.Model):
    """
    验证码表
    """
    __tablename__ = 'verification_codes'
    
    # 主键，自动递增
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    # 6位数字验证码
    code = db.Column(db.String(6), nullable=False, comment='验证码')
    # 手机号
    phone = db.Column(db.String(11), nullable=False, index=True, comment='手机号')
    # 是否已使用
    is_used = db.Column(db.Boolean, default=False, comment='是否已使用')
    # 创建时间
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')

    def __repr__(self):
        return f'<VerificationCode {self.phone}:{self.code}>' 

class Collection(db.Model):
    """收藏夹表"""
    __tablename__ = 'collections'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    user_id = db.Column(db.Integer, nullable=False, index=True, comment='用户ID')
    name = db.Column(db.String(50), nullable=False, comment='收藏夹名称')
    type = db.Column(db.Integer, nullable=False, default=0, index=True, comment='收藏夹类型：0-默认收藏夹，1-自定义收藏夹')
    sort = db.Column(db.Integer, nullable=False, default=0, comment='排序')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'name': self.name,
            'type': self.type,
            'sort': self.sort,
            'create_time': int(datetime.timestamp(self.create_time)) if self.create_time else None,
            'update_time': int(datetime.timestamp(self.update_time)) if self.update_time else None
        } 

class CollectionItem(db.Model):
    """收藏内容表"""
    __tablename__ = 'collection_items'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    collection_id = db.Column(db.Integer, nullable=False, index=True, comment='收藏夹ID')
    user_id = db.Column(db.Integer, nullable=False, index=True, comment='用户ID')
    title = db.Column(db.String(255), nullable=False, comment='标题')
    cover = db.Column(db.String(255), nullable=True, comment='封面图')
    url = db.Column(db.String(255), nullable=False, comment='链接地址')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    def to_dict(self):
        return {
            'id': self.id,
            'collection_id': self.collection_id,
            'user_id': self.user_id,
            'title': self.title,
            'cover': self.cover,
            'url': self.url,
            'create_time': int(datetime.timestamp(self.create_time)) if self.create_time else None,
            'update_time': int(datetime.timestamp(self.update_time)) if self.update_time else None
        } 

class BrowseRecord(db.Model):
    """浏览记录表"""
    __tablename__ = 'browse_records'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
    user_id = db.Column(db.Integer, nullable=False, index=True, comment='用户ID')
    article_id = db.Column(db.Integer, nullable=False, index=True, comment='文章ID')
    title = db.Column(db.String(255), nullable=False, comment='标题')
    cover = db.Column(db.String(255), nullable=True, comment='封面图')
    url = db.Column(db.String(255), nullable=False, comment='链接地址')
    browse_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, index=True, comment='浏览时间')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    __table_args__ = (
        db.UniqueConstraint('user_id', 'article_id', name='uk_user_article'),
    )

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'article_id': self.article_id,
            'title': self.title,
            'cover': self.cover,
            'url': self.url,
            'browse_time': int(datetime.timestamp(self.browse_time)) if self.browse_time else None,
            'create_time': int(datetime.timestamp(self.create_time)) if self.create_time else None,
            'update_time': int(datetime.timestamp(self.update_time)) if self.update_time else None
        } 